package tc.jv.task12;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import tc.jv.task4.Vector;
import tc.jv.task9.IncompatibleVectorSizeException;

public class Vectors extends tc.jv.task8.Vectors
{

	public static Vector add(Vector v1, Vector v2) throws IncompatibleVectorSizeException
	{
		Vector nv = createInstance(v1, v1.size());
		nv.fill(v1);
		nv.sum(v2);
		return nv;
	}
	
	public static Vector multiply(Vector v, double num)
	{
		Vector nv = createInstance(v, v.size());
		try
		{
			nv.fill(v);
		}
		catch (IncompatibleVectorSizeException e)
		{
			e.printStackTrace();
		}
		nv.multiply(num);
		return nv;
	}
	
	public static Vector createInstance(Vector sample)
	{
		return createInstance(sample, 0);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Vector createInstance(Object sample, int size)
	{
		Class sampleClass = sample.getClass();
		try
		{
			Constructor constructor = sampleClass.getConstructor(Integer.TYPE);
			
			try
			{
				return (Vector) constructor.newInstance(Integer.valueOf(size));
			}
			catch (IllegalArgumentException e)
			{
				System.err.println("Illegal argument");
			}
			catch (InstantiationException | IllegalAccessException 
					| InvocationTargetException e)
			{
				e.printStackTrace();
			}
		}
		catch (NoSuchMethodException e)
		{
			System.err.println("No such constructors!");
			return createInstance(size);
		}
		catch (SecurityException e)
		{
			e.printStackTrace();
		}

		return null;
	}
	
}
